var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var app = getApp();

Page({
  data: {
    bannerInfo: {
      'imgUrl': 'https://wh.nazhiyun.com/home/youtao/imgs/killMore2x.png',
      'name': '准时开抢'
    },
    goodsList: [],
    datetimeTo: "", // 秒杀结束时间
    reT: [], // 剩时间（时分秒）
    page: 1,
    size: 10,
    totalPages: 1
  },
  getGoodsList: function () {
    var that = this;
    util.request(api.GoodsList, {
        isHot: true,
        page: that.data.page,
        size: that.data.size
      })
      .then(function (res) {
        if (res.errno === 0) {
          console.log(res.data.killEndTime);
          that.setData({
            datetimeTo: res.data.killEndTime,
            goodsList: that.data.goodsList.concat(res.data.goodsList),
            totalPages: res.data.totalPages
          });
        }
      });

  },
  onLoad: function (options) {
    this.getGoodsList();
  },
  onReady: function () {},
  onShow: function () {
    this.data.timer = setInterval(() => {
      this.setData({
        reT: util.getTimeLeft(this.data.datetimeTo)
      });
      if (this.data.reT && this.data.reT.hou == "00" && this.data.reT.min == "00" && this.data.reT.sec == "00") {
        clearInterval(this.data.timer);
      }
    }, 1000);
  },
  onHide: function () {},
  onUnload: function () {},
  onReachBottom: function () {
    if (this.data.totalPages > this.data.page) {
      this.setData({
        page: this.data.page + 1
      });
    } else {
      wx.showToast({
        title: '已经到底了!',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    this.getGoodsList();
  },
  //立即购买
  addFast: function (e) {
    var that = this;
    util.request(api.CartFastAdd, {
        goodsId: e.currentTarget.dataset.id,
        number: 1
      }, "POST")
      .then(function (res) {
        if (res.errno == 0) {
          try {
            wx.setStorageSync('cartId', res.data);
            wx.setStorageSync('grouponRulesId', 0);
            wx.setStorageSync('grouponId', -1);
            wx.navigateTo({
              url: '/pages/checkout/checkout'
            })
          } catch (e) {}
        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: res.errmsg,
            mask: true
          });
        }
      });
  }
})